package com.kantboot.api.email.service.impl;

import com.kantboot.api.email.domain.dto.ApiEmailSearchDTO;
import com.kantboot.api.email.domain.dto.EmailSendDTO;
import com.kantboot.api.email.domain.entity.ApiEmail;
import com.kantboot.api.email.event.SendEmailEvent;
import com.kantboot.api.email.repository.ApiEmailRepository;
import com.kantboot.api.email.service.IApiEmailService;
import com.kantboot.util.core.param.PageParam;
import com.kantboot.util.core.result.PageResult;
import jakarta.annotation.Resource;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;

@Service
public class ApiEmailServiceImpl implements IApiEmailService {

    private final ApplicationEventPublisher applicationEventPublisher;

    public ApiEmailServiceImpl(ApplicationEventPublisher applicationEventPublisher) {
        this.applicationEventPublisher = applicationEventPublisher;
    }

    @Resource
    private ApiEmailRepository repository;

    @Override
    public ApiEmail send(EmailSendDTO dto) {
        Boolean isHtml = dto.getIsHtml();
        if (isHtml == null) {
            isHtml = false;
        }

        ApiEmail apiEmail= new ApiEmail()
                .setTypeCode(dto.getTypeCode())
                .setTo(dto.getTo())
                .setSubject(dto.getSubject())
                .setContent(dto.getContent())
                .setIsHtml(isHtml)
                .setStatusCode(ApiEmail.STATUS_CODE_SENDING);
        ApiEmail result = repository.save(apiEmail);
        SendEmailEvent sendEmailEvent = new SendEmailEvent(this, result);  // 创建事件
        applicationEventPublisher.publishEvent(sendEmailEvent);  // 发布事件
        return result;
    }


    @Override
    public PageResult getBodyData(PageParam<ApiEmailSearchDTO> pageParam) {
        return PageResult.of(repository.getBodyData(pageParam.getData(),pageParam.getPageable()));
    }
}
